package com.techie.mdm.appbar.showcase.binding;

import org.jdesktop.beansbinding.*;
import org.springframework.binding.MutablePropertyAccessStrategy;
import org.springframework.binding.PropertyAccessStrategy;
import org.springframework.binding.form.FormModel;
import org.springframework.binding.support.BeanPropertyAccessStrategy;
import org.springframework.binding.value.ValueModel;
import org.springframework.binding.value.support.MessageFormatValueModel;
import org.springframework.binding.value.support.ValueHolder;
import org.springframework.richclient.form.FormModelHelper;

import java.awt.*;

/**
 * todo - this has little to do with rectangles. Just take a list of property paths, and
 * bind these to parameters.
 */
public class DynamicFormatString
{

    public static ValueModel createModel(ValueModel source, String[] propertyPaths,
                                         ValueModel/*<Object>*/ whenNull,
                                         ValueModel/*<String>*/ formatModel)
    {
        MutablePropertyAccessStrategy propertyAccess = new BeanPropertyAccessStrategy(source);

        ValueModel[] arguments = buildValueModels(propertyAccess, propertyPaths);
        return createModel(arguments, whenNull, formatModel);
    }

    public static ValueModel createModel(ValueModel[] arguments,
                                         ValueModel/*<Object>*/ whenNull,
                                         ValueModel/*<String>*/ formatModel)
    {
        // prime with initial value
        String format = formatModel.getValue().toString();

        DynamicMessageFormatValueModel targetModel =
                new DynamicMessageFormatValueModel(format, arguments);
        // update the message format when the format string changes
        Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ,
                formatModel, BeanProperty.create(ValueModel.VALUE_PROPERTY),
                targetModel, BeanProperty.create(DynamicMessageFormatValueModel.PATTERN)).bind();

        ValueModel result =
            (whenNull!=null) ?
                EmptySwitch.createSwitch(targetModel, whenNull)
                    : targetModel;
        return result;
    }

    private static ValueModel[] buildValueModels(MutablePropertyAccessStrategy access, String[] propertyPaths)
    {
        ValueModel[] result = new ValueModel[propertyPaths.length];
        for (int i = 0; i < propertyPaths.length; i++)
        {
            String propertyPath = propertyPaths[i];
            result[i] = vm(access, propertyPath);
        }
        return result;
    }

    private static ValueModel vm(MutablePropertyAccessStrategy access, String property)
    {
        return access.getPropertyValueModel(property);
    }

}
